package handels

import (
	"coconut-latte/cache"
	"coconut-latte/models"
	"coconut-latte/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user models.User
	//判断
	redis_key := "user_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount == 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误超过3次需要限制登录2小时",
		})
		return
	}
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
		if errCount == 2 {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误超过3次需要限制登录2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func RoleAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserRole(c *gin.Context) {
	id := c.Query("id")

	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.uid = roles.id
		WHERE
		  user_roles.uid = 1
	*/
	var role models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.uid = roles.id").
		Where("user_roles.uid = ?", id).
		First(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return
}
func UserNode(c *gin.Context) {
	id := c.Query("id")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.id = 1
	*/
	var node models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.id = ?", id).
		First(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
	return
}
func CarAdd(c *gin.Context) {
	carno := c.PostForm("carno")     //车辆编码
	carname := c.PostForm("carname") //车辆 名称
	carcode := c.PostForm("carcode") //车牌照
	if carno == "" || carname == "" || carcode == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Car{
		CarNo:   carno,
		CarName: carname,
		CarCode: carcode,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func CarOrderAdd(c *gin.Context) {
	orderno := c.PostForm("orderno")
	orderfrom := c.PostForm("orderfrom")
	orderto := c.PostForm("orderto")
	ordergood := c.PostForm("ordergood")
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	if orderto == "" || orderno == "" || orderfrom == "" || ordergood == "" || cid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.CarOrder{
		OrderNo:   orderno,
		OrderFrom: orderfrom,
		OrderTo:   orderto,
		OrderGood: ordergood,
		Cid:       cid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	/*
		SELECT
		  cars.car_no as CarNo,
		  cars.car_name as CarName,
		  cars.car_code as CarCode,
		  car_orders.order_no as OrderNo,
		  car_orders.order_from as OrderFrom,
		  car_orders.order_to as OrderTo,
		  car_orders.order_good as OrderGood

		FROM
		  car_orders
		  LEFT JOIN cars on cars.id = car_orders.cid
	*/
	var data []models.CarOrderList
	redis_key := "redis_key_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table(" car_orders").
			Select(
				"cars.car_no as CarNo",
				"cars.car_name as CarName",
				"cars.car_code as CarCode",
				"car_orders.order_no as OrderNo",
				"car_orders.order_from as OrderFrom",
				"car_orders.order_to as OrderTo",
				"car_orders.order_good as OrderGood",
			).
			Joins("LEFT JOIN cars on cars.id = car_orders.cid").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}

	var total int64
	models.DB.Model(&models.CarOrder{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  data,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var data []models.CarOrderList
	redis_key := "redi_list" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table(" car_orders").
			Select(
				"cars.car_no as CarNo",
				"cars.car_name as CarName",
				"cars.car_code as CarCode",
				"car_orders.order_no as OrderNo",
				"car_orders.order_from as OrderFrom",
				"car_orders.order_to as OrderTo",
				"car_orders.order_good as OrderGood",
			).
			Joins("LEFT JOIN cars on cars.id = car_orders.cid").
			Where("car_orders.id = ?", id).
			Debug().
			Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return
}
